package leetcode23

import "math"

type ListNode struct {
	Val  int
	Next *ListNode
}

// 过滤nil
// 按序排序
// 过滤nil
func mergeKLists(lists []*ListNode) *ListNode {

	head := &ListNode{}
	next := head
	min := math.MaxInt32
	index := 0
	lists = makeNewList(lists)
	if len(lists) == 0 {
		return nil
	}
	for {
		for i := range lists {

			if lists[i] != nil && lists[i].Val <= min {
				min = lists[i].Val
				index = i
			}
		}
		next.Val = lists[index].Val
		lists[index] = lists[index].Next

		lists = makeNewList(lists)
		if len(lists) == 0 {
			return head
		}

		next.Next = &ListNode{}
		next = next.Next
		min = math.MaxInt32
	}
}

func makeNewList(lists []*ListNode) []*ListNode {
	newList := make([]*ListNode, 0)
	for i := range lists {
		if lists[i] != nil {
			newList = append(newList, lists[i])
		}
	}
	return newList
}
